<?php

class FieldModel
{

  public $model;

  public function __construct($model = array())
  {
    if ($model instanceof FieldModel) {
      $model = $model->model;
    }

    $this->model = (array) $model;

    if (preg_match('/^\s*(?:([a-z_][a-z0-9_]*)\s*\.\s*)?([a-z_][a-z0-9_]*)(?:\s+AS\s+([a-z_][a-z0-9_]*))?\s*$/im', $this->getName(), $parts)) {
      if (! empty($parts[1])) $this->model['table'] = $parts[1];
      if (! empty($parts[2])) $this->model['name'] = $parts[2];
      if (! empty($parts[3])) $this->model['alias'] = $parts[3];
    }
  }

  public function getSql($default = null)
  {
    $sql = null;

    if (isset($this->model['sql'])) {
      $sql = $this->model['sql'];
    }
    else {
      $table = $this->getTable($default);
      $name = $this->getName();

      $sql = '';

      if (! empty($table)) {
        $sql = "`$table`.";
      }

      $sql .= "`$name`";

      if (isset($this->model['alias'])) {
        $sql .= " AS `{$this->model['alias']}`";
      }
    }

    return $sql;
  }

  public function getFullName($default = null)
  {
    return implode('.', array_filter(array($this->getTable($default), $this->getName())));
  }

  public function getName()
  {
    if (! isset($this->model['name'])) {
      if (is_array($this->model) && isset($this->model[0])) {
        $this->model['name'] = $this->model[0];
      }
      else {
        throw new DomainDefinitionException('Could not determine field name');
      }
    }

    return $this->model['name'];
  }

  public function getMapper()
  {
    if (empty($this->model['mapper'])) {
      $type = $this->getType();

      if (! empty($type) && is_subclass_of($type, 'DataMapper')) {
        $this->model['mapper'] = new $type($this);
      }
      else {
        $this->model['mapper'] = new DefaultDataMapper($this, $type);
      }
    }
    elseif (! ($this->model['mapper'] instanceof DataMapper)) {
      $class = $this->model['mapper'];

      if (is_subclass_of($class, 'DataMapper')) {
        $this->model['mapper'] = new $class($this);
      }
      else {
        throw new DomainDefinitionException("Mapper <b>$class</b> must extend DataMapper or one of it's subclasses");
      }
    }

    return $this->model['mapper'];
  }

  public function getType()
  {
    $type = null;

    if (isset($this->model['type'])) {
      $type = $this->model['type'];
    }
    elseif (is_array($this->model) && isset($this->model[1])) {
      $type = $this->model[1];
    }

    return $type;
  }

  public function getTable($default = null)
  {
    return isset($this->model['table']) ? $this->model['table'] : $default;
  }

}
